import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ljy_p_app/config/config.dart';
import 'package:ljy_p_app/constans/lj_constans.dart';
import 'package:ljy_p_app/diffwidget/ljy_flex_button.dart';
import 'package:ljy_p_app/local/local_storage.dart';
import 'package:ljy_p_app/localization/localization_key.dart';
import 'package:ljy_p_app/model/common_list_datatype.dart';
import 'package:ljy_p_app/pages/common/user_theme_controller.dart';
import 'package:ljy_p_app/routes/lj_routes.dart';
import 'package:ljy_p_app/style/lj_style.dart';
import 'package:ljy_p_app/utils/common_utils.dart';
import 'package:ljy_p_app/utils/navigator_utils.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomeDrawer extends StatefulWidget {
  const HomeDrawer({super.key});

  @override
  State<HomeDrawer> createState() => _HomeDrawerState();
}

class _HomeDrawerState extends State<HomeDrawer> {
  final username = 'xiandao is champion';
  String email = '';

  //final UserThemeController themeController = Get.put(UserThemeController());

  @override
  void initState() {
    super.initState();
    initData();
  }

  void initData() async {
    email = await LocalStorage.get(Config.USER_NAME_KEY);
    setState(() {
    });
  }

  showThemeDialog(BuildContext context) {
    StringList list = [
      LocalizationKey.homeThemeDefault.tr,
      LocalizationKey.homeTheme1.tr,
      LocalizationKey.homeTheme2.tr,
      LocalizationKey.homeTheme3.tr,  
      LocalizationKey.homeTheme4.tr,
      LocalizationKey.homeTheme5.tr,
      LocalizationKey.homeTheme6.tr,
    ];
    CommonUtils.showCommitOptionDialog(context, list, (index) {
      final UserThemeController themeController = Get.find<UserThemeController>();
      themeController.setThemeIndex(index);
    }, colorList: CommonUtils.getThemeListColor());
  }

  _changeGreyMode() {
    final UserThemeController themeController = Get.find<UserThemeController>();
    themeController.isGreyMode.value = !themeController.isGreyMode.value;
  }

  showAboutDialog(BuildContext context, String? versionName) {
    versionName ??= "Null";
    NavigatorUtils.showLJYDialog(context: context, builder: (context) {
      return AboutDialog(
        applicationName: LocalizationKey.appName.tr,
        applicationVersion: "${LocalizationKey.appVersion.tr}: ${versionName ?? ""}",
        applicationIcon: Image(
          image: AssetImage(LJICons.DEFAULT_USER_ICON),
          width: 50.0,
          height: 50.0),
        applicationLegalese: '© 2024 xiandao',
      );
    });
  }


  void loginOut() async {
    NavigatorUtils.showLJYDialog(context: context, builder: (context) {
      return Center(
        child: Container(
          height: 150,
          width: MediaQuery.of(context).size.width * 0.8,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Column(
            children: [
              Container(
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(color: Color.fromARGB(255, 220, 220, 220), width: 0.5)
                  )
                ),
                height: 90,
                child: Center(
                  child: Text(
                    "确定要退出登录吗？",
                    style: TextStyle(
                      color: LJColors.mainTextColor,
                      fontSize: 18.0,
                      height: 1.0
                    ),
                  ),
                ),
              ),
              Expanded(child: Row(
                children: [
                  Expanded(child: GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Center(child: Text('取消', style: TextStyle(
                      color: LJColors.mainTextColor,
                      fontSize: 16.0,
                    ),)),
                  )),
                  VerticalDivider(
                    color: Color.fromARGB(255, 220, 220, 220),
                    width: 0.5,
                    thickness: 0.5,
                  ),
                  Expanded(child: GestureDetector(
                    onTap: () async {
                      SharedPreferences pref = await SharedPreferences.getInstance();
                    pref.setBool(LjConstans.isLoginKey, false);
                    /// 未登录
                    Get.offAllNamed(LjRoutes.login);
                    },
                    child: Center(child: Text('退出', style: TextStyle(
                      color: const Color.fromARGB(255, 67, 178, 140),
                      fontSize: 16.0,
                      fontWeight: FontWeight.bold
                    ),)),
                  )),
                ],
              )
              ),
            ],
          ),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Drawer(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(0)
        ),
        ///侧边栏按钮Drawer
        child: Container(
          //默认背景
          color: Theme.of(context).primaryColor,
          child: SingleChildScrollView(
            child: Container(
              constraints: BoxConstraints(
                minHeight: MediaQuery.sizeOf(context).height
              ),
              child: Material(
                color: LJColors.white,
                child: Column(
                  children: [
                    // material内置控件
                    UserAccountsDrawerHeader(
                      accountName: Text(username, style: LJConstant.largeTextWhite),
                      accountEmail: Text(email, style: LJConstant.normalTextLight),
                      
                      // 头像
                      currentAccountPicture: GestureDetector(
                        onTap: () {},
                        child: CircleAvatar(
                          // 圆形图标控件
                          backgroundImage: NetworkImage(LJICons.DEFAULT_REMOTE_PIC),
                        ),
                      ),
                      decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor,
                      ),
                    ),
                    ListTile(
                      title: Text(LocalizationKey.homeReply.tr, style: LJConstant.normalText),
                      onTap: () {
                        String content = '';
                        CommonUtils.showEditDialog(
                        context,
                        LocalizationKey.homeReply.tr,
                        (title) {},
                        (res) {
                          content = res;
                        },
                        () {
                          if (content.isEmpty) {
                            return;
                          }
                          CommonUtils.showLoadingDialog(context);

                          Future.delayed(const Duration(seconds: 2), () {
                            Navigator.pop(context);
                            Navigator.pop(context);
                          });
                        },
                        titleController: TextEditingController(),
                        valueController: TextEditingController(),
                        needTitle: false,
                        hintText: LocalizationKey.feedBackTip.tr);
                      },
                    ),
                    ListTile(
                      title: Text(LocalizationKey.homeHistory.tr, style: LJConstant.normalText),
                      onTap: () {
                        NavigatorUtils.gotoCommonList(
                          context,
                          LocalizationKey.homeHistory.tr,
                          "repositoryql",
                          CommonListDatatype.history,
                          userName: "",
                          reposName: "");
                      },
                    ),
                    ListTile(
                      title: Hero(tag: 'home_user_info', child: Material(
                        color: Colors.transparent,
                        child: Text(LocalizationKey.homeUserInfo.tr, style: LJConstant.normalTextBold),
                      )),
                      onTap: () {
                        NavigatorUtils.gotoUserProfileInfo(context);
                      },
                    ),
                    ListTile(
                      title: Text(LocalizationKey.homeChangeTheme.tr, style: LJConstant.normalText),
                      onTap: () {
                        showThemeDialog(context);
                      },
                    ),
                    ListTile(
                      title: Text(LocalizationKey.homeChangeLanguage.tr, style: LJConstant.normalText),
                      onTap: () {
                        CommonUtils.showLanguageDialog(context);
                      },
                    ),
                    ListTile(
                      title: Text(LocalizationKey.homeChangeGrey.tr, style: LJConstant.normalText),
                      onTap: () {
                        _changeGreyMode();
                      },
                    ),
                    ListTile(
                      title: Text(LocalizationKey.homeCheckUpdate.tr, style: LJConstant.normalText),
                      onTap: () {
                        if (Platform.isIOS) {
                          return;
                        }
                      },
                    ),
                    ListTile(
                      title: Text(LocalizationKey.homeAbout.tr, style: LJConstant.normalText),
                      onTap: () {
                        PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
                          String version = packageInfo.version;
                          showAboutDialog(context, version);
                        });
                      },
                      onLongPress: () {
                        /// debug页面
                      },
                    ),
                    ListTile(
                      title: LjyFlexButton(
                        text: LocalizationKey.loginOut.tr,
                        color: Colors.redAccent,
                        textColor: LJColors.textWhite,
                        onPress: () {
                          loginOut(); 
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}